<?php

namespace Home\Controller;

class CourierCodeController extends BaseController {

    private $model = null;

    function __construct() {
        parent::__construct();
        $this->menu = 3;
        $this->model = D('CourierCode');
    }

    function index() {
        $this->display();
    }

    function CourierCodeList() {
        $where = array('status' => 0);
        $key = I('get.key', '', 'trim');
        if ($key != '') {
            $where['state'] = array('LIKE', "%{$key}%");
        }
        $result = $this->model->getList($where);
        $this->assign('data', $result);
        $state = $this->model->getState();
        $this->assign('state', $state);
        $category = $this->model->getCategory();
        $this->assign('category', $category);
        $this->display();
    }

    function MyCourierCodeList() {
        $where = array('user_id' => parent::$user_id, 'is_deleted' => 1);
        $key = I('get.key', '', 'trim');
        if ($key != '') {
            $where['courier_num|state|category|source'] = array('LIKE', "%{$key}%");
        }
        $result = $this->model->getMyCourierCodeList($where);
        $this->assign('data', $result);
        $state = $this->model->getState();
        $this->assign('state', $state);
        $category = $this->model->getCategory();
        $this->assign('category', $category);
        $this->display();
    }

    function getCourierCode() {
        if (IS_POST) {
            $return = array('info' => '提交失败！', 'status' => 0);
            M()->startTrans(); //开启事务
            try {
                $courier_code_id = I('post.CourierCodeId', 0, 'intval');
                $courier_info = $this->model->getCourierInfo($courier_code_id);
                if ($courier_info['status'] == 1) {
                    E('对不起，快递单号已被领取或购买！');
                }
                $order_num = $this->model->getOrderNum(parent::$user_id);
                $num = sysconf('free_num');
                if ($order_num >= $num) {
                    E('对不起，一天最多只能领取' . $num . '个免费快递单号！');
                }
                $data1[] = array(
                    'type' => 1,
                    'courier_id' => $courier_info['id'],
                    'user_id' => parent::$user_id,
                    'user_name' => parent::$user_name,
                    'courier_num' => $courier_info['coding'],
                    'price' => $courier_info['price'],
                    'state' => $courier_info['state'],
                    'category' => $courier_info['category'],
                    'source' => '免费领取',
                    'internet_time' => $courier_info['internet_time'],
                    'add_time' => time()
                );
                $result1 = $this->model->addCourier($data1);
                if (!$result1) {
                    //订单生成失败
                    E('对不起，领取失败！');
                }
                $result2 = $this->model->modifyCourierStatus($courier_code_id);
                if ($result2 === false) {
                    //单号状态修改失败
                    E('对不起，领取失败！');
                }
                M()->commit(); //提交事务
                $return['status'] = 1;
                $return['info'] = '领取成功！';
            } catch (\Exception $e) {
                M()->rollback(); //回滚
                $return['status'] = 0;
                $return['info'] = $e->getMessage();
            }
            $this->ajaxReturn($return);
        }
    }

    function PayCourierCode() {
        if (IS_POST) {
            $model = M();
            $return = array('info' => '购买失败！', 'status' => 0);
            $model->startTrans(); //开启事务
            try {
                $courier_ids = I('post.CourierCodeId', 0, 'trim');
                $courier_info = $this->model->getCourierList($courier_ids);
                $user_info = $this->model->getUserIndo(parent::$user_id);
                $data1 = array();
                $total_price = 0;
                foreach ($courier_info as $key => $val) {
                    if ($val['status'] == 1) {
                        E('对不起，快递单号已被领取或购买！');
                        break;
                    }
                    $data1[] = array(
                        'type' => 2,
                        'courier_id' => $val['id'],
                        'user_id' => parent::$user_id,
                        'user_name' => parent::$user_name,
                        'courier_num' => $val['coding'],
                        'price' => $val['price'],
                        'state' => $val['state'],
                        'category' => $val['category'],
                        'source' => '购买',
                        'internet_time' => $val['internet_time'],
                        'add_time' => time()
                    );
                    $total_price += $val['price'];
                }
                $result1 = $this->model->addCourier($data1);
                if (!$result1) {
                    //订单生成失败
                    E('对不起，购买失败！');
                }
                $result2 = $this->model->modifyCourierStatus($courier_ids);
                if ($result2 === false) {
                    //单号状态修改失败
                    E('对不起，购买失败！');
                }
                $amount = $user_info['amount'] - $total_price;
                if (($user_info['amount'] < $total_price) || $amount < 0) {
                    E('余额不足，购买失败！');
                }
                $result3 = $this->model->modifyUserAmount(parent::$user_id, $amount);
                if ($result3 === false) {
                    //用户余额修改失败
                    E('对不起，购买失败！');
                }
                $model->commit(); //提交事务
                $return['status'] = 1;
                $return['info'] = '购买成功！';
            } catch (\Exception $e) {
                $model->rollback(); //回滚
                $return['status'] = 0;
                $return['info'] = $e->getMessage();
            }
            $this->ajaxReturn($return);
        }
    }

    function FreeCourierCodeDel() {
        if (IS_POST) {
            $ids = I('post.CourierCodeId', '', 'trim');
            $result = $this->model->FreeCourierCodeDel($ids);
            if ($result !== false) {
                $this->success('删除成功！');
            } else {
                $this->error('删除失败！');
            }
        }
    }

    function export() {
        $obj_PHPExcel = new \PHPExcel();
        //设置标题
        $obj_PHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A1', '快递单号')
                ->setCellValue('B1', '国家')
                ->setCellValue('C1', '单号类别')
                ->setCellValue('D1', '上传时间');
        //设置单元格居中
//        $obj_PHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
//        $obj_PHPExcel->getDefaultStyle()->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        //设置列宽
        $obj_PHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
        $obj_PHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
        $obj_PHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
        $obj_PHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
        $list = $this->model->getExportList(parent::$user_id);
        foreach ($list as $key => $vo) {
            $num = $key + 2;
            $obj_PHPExcel->getActiveSheet()->setCellValue('A' . $num, $vo['courier_num']);
            $obj_PHPExcel->getActiveSheet()->setCellValue('B' . $num, $vo['state']);
            $obj_PHPExcel->getActiveSheet()->setCellValue('C' . $num, $vo['category']);
            $obj_PHPExcel->getActiveSheet()->setCellValue('D' . $num, date('Y/m/d', $vo['add_time']));
        }
        $obj_writer = \PHPExcel_IOFactory::createWriter($obj_PHPExcel, 'Excel5');
        $filename = '快递单号-' . date('Y-m-d H-i-s') . ".xls"; //文件名
        //设置header
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename=' . $filename);
        $obj_writer->save('php://output'); //输出
        exit;
    }

}
